//
//  LMAVManager.m
//  EPA
//
//  Created by lanou3g on 16/4/21.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "LMAVManager.h"

@interface LMAVManager ()
/*
 .h中的是只读属性，在这里是要用到AVPlayer
 */
@property (nonatomic, strong) AVPlayer *player;



@end

@implementation LMAVManager

+ (instancetype)shareManager{
    static LMAVManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
            manager = [LMAVManager new];
            manager.player = [[AVPlayer alloc]init];
        }
    });
    return manager;
}

-(void)play{
    
    AVPlayerItem *item = self.itemArray[self.currentIndex];
    [self.player replaceCurrentItemWithPlayerItem:item];
    [self.player play];
    _playerState = PlayerStatePlay;
}

-(void)pause{
    [self.player pause];
    _playerState = PlayerStatePause;
}

- (void)stop{
    [self seekToNewTime:0];
    [self pause];
}

- (void)previous{
    self.currentIndex --;
    if (self.currentIndex < 0) {
        self.currentIndex = self.itemArray.count - 1;
    }
    [self play];
}

- (void)next{
    self.currentIndex ++;
    if (self.currentIndex >= self.itemArray.count) {
        self.currentIndex = 0;
    }
    [self play];
}

- (void)seekToNewTime:(float)time{
    CMTime newTime = _player.currentTime;
    newTime.value = newTime.timescale * time;
    [_player seekToTime:newTime];
}


-(void)seekToTime:(CMTime)time{
    [self.player seekToTime:time];
}

-(float)currentTime{
    if (_player.currentItem.timebase == 0) {
        return 0;
    }
    return _player.currentTime.value / _player.currentTime.timescale;
}

-(float)totalTime{
    if (_player.currentItem.duration.timescale == 0) {
        return 0;
    }
    return _player.currentItem.duration.value / _player.currentItem.duration.timescale;
}

- (void)playerDidFinishTotalTime:(float )time{
    if (time == self.totalTime) {
        [self next];
    }
}

@end
